<?php
/**
 * Created by PhpStorm.
 * User: wanglin
 * Date: 2018/11/7
 * Time: 14:07
 */

namespace App\Services;

use App\Models\ActiveRecord;
use App\Models\Agent;
use App\Models\AgentBkgeFeeSetting;
use App\Models\AgentBkgeFeeSettingLog;
use App\Models\AgentBkgeGlobalSetting;
use App\Models\AgentBkgeRecord;
use App\Models\AgentBkgePeriod;
use App\Models\AgentBkgeSetting;
use App\Models\AgentProperty;
use App\Models\AgentRebetSetting;
use App\Models\MoneyDeposit;
use App\Models\MoneyLog;
use App\Models\MoneyWithdraw;
use App\Models\ReportPartnerGame;
use App\Models\Setting;
use App\Models\User;
use common\enum\CommonEnum;
use common\enum\MoneyDepositEnum;
use common\enum\MoneyWithdrawEnum;
use Illuminate\Support\Facades\DB;


/**
 * 退佣计算相关逻辑
 * Class BkgeService
 * @package App\Services
 */
class BkgeService
{
    //setting表key值，用于获取配置
    const SYERTEM_CONFIG = 'BASIC_SETTING';

    /**
     * 获取系统佣金发放配置
     * @param int $hall_id
     * @return array
     */
    public static function getSysSeting(int $hall_id): array
    {
        $result = AgentBkgeGlobalSetting::where('hall_id', $hall_id)->select('send_type', 'auto_amount_min')->first();
        if (empty($result)) {
            return ['send_type' => 0, 'auto_amount_min' => 0];
        }
        return $result->toArray();
    }

    /**
     * 获取本期统计时间对应的期数
     * @param int $hall_id
     * @return array
     */
    public static function getPeriodInfo(int $hall_id): array
    {
        $time = time();
        $data = AgentBkgePeriod::whereRaw("status=0 and hall_id={$hall_id} and unix_timestamp(handle_time) <= {$time} ")->orderBy('id', 'desc')->first();
        if (empty($data)) {
            return [];
        }
        return $data->toArray();
    }


    /**
     * 获取本期需要统计的代理列表
     * 只统计直属代理
     * @param int $hall_id
     * @param array $currend_period_info
     * @return array
     */
    public static function getAgentList(int $hall_id): array
    {
        $list = Agent::where('hall_id', $hall_id)->where('type', 1)->where("status", 1)->select("id", "agent_name")->orderBy('id', "desc")->get();
        if (!empty($list)) {
            return json_decode(json_encode($list), true);
        }
        return [];
    }

    /**
     * 获取代理的相关信息
     * @param int $id
     * @return array
     */
    public static function getAgentInfo(int $id): array
    {
        $agent_info = Agent::where("id", $id)->select("id", "hall_id", "pid", "type", "agent_name", "status")->first()->toArray();
        $agent_prop = AgentProperty::where('agent_id', $id)->select("bkge_template_id", "rebet_template_id", 'register_source')->first()->toArray();
        return array_merge($agent_info, $agent_prop);
    }


    /**
     * 获取有效会员数
     * @param int $agent_id
     * @param array $currend_period_info
     * @param int $hall_id
     * @return array
     */
    public static function getOfflineAgentValidCount(int $agent_id, array $currend_period_info, int $hall_id, array $config): int
    {
        $startTime = date("Y-m-d", strtotime($currend_period_info['start_time']));
        $endTime = date("Y-m-d", strtotime($currend_period_info['end_time']) + 1);
        //获取该代理所绑定的会员id
        $user_ids = self::getAgentMember($agent_id, $hall_id, date("Y-m-d H:i:s", strtotime($currend_period_info['end_time']) + 1));
        if (empty($user_ids)) {
            return 0;
        }

        //如果有效投注为0 或存款为0 则所有会员都是有效会员
        if ($config['effective_bet_amount'] == 0 || $config['deposit_amount'] == 0) {
            return count($user_ids);
        }
        $res1 = ReportPartnerGame::where("hall_id",$hall_id)->where('date',">=",$startTime)->where("date","<",$endTime)
            ->selectRaw("SUM(validbet) as validbet,user_id")
            ->whereIn('user_id', $user_ids)
            ->groupBy('user_id')
            ->havingRaw(" validbet >=" . intval($config['effective_bet_amount']))->get();
        if (!empty($res1)) {
            $res1 = json_decode(json_encode($res1, JSON_UNESCAPED_UNICODE), true);
            $bet_ids = array_column($res1, 'user_id');
        } else {
            $res1 = [];
            $bet_ids = [];
        }
        $diff_ids = array_diff($user_ids, $bet_ids);//用这些去查存款大于配置的.
        $depositType = [
            MoneyDepositEnum::DEPOSIT_TYPE_COUNTER, MoneyDepositEnum::DEPOSIT_TYPE_ATM, MoneyDepositEnum::DEPOSIT_TYPE_AUTO_ATM,
            MoneyDepositEnum::DEPOSIT_TYPE_MOBILE, MoneyDepositEnum::DEPOSIT_TYPE_ALIPAY,
            MoneyDepositEnum::DEPOSIT_TYPE_TENPAY, MoneyDepositEnum::DEPOSIT_TYPE_WECHAT,
            MoneyDepositEnum::DEPOSIT_TYPE_MANUAL, MoneyDepositEnum::DEPOSIT_TYPE_CYBER_BANK];
        $depositType=implode(",",$depositType);
        $is_online=MoneyDepositEnum::IS_ONLINE_TRUE;
        $no_online=MoneyDepositEnum::IS_ONLINE_FALSE;
        $where = "((is_online={$no_online} and offline_pay_type in ({$depositType})) or  (is_online= {$is_online}))";
        $res2 = MoneyDeposit::where("status",MoneyDepositEnum::STATUS_PAID)->where("hall_id",$hall_id)->where('recharge_time',">=",$startTime . " 00:00:00")
            ->whereRaw($where)->where('recharge_time',"<", $endTime . " 00:00:00")->selectRaw("sum(amount) money,user_id")
            ->whereIn('user_id', $diff_ids)
            ->groupBy('user_id')->havingRaw("money >=" . intval($config['deposit_amount']))->get()->toArray();
        if (!empty($res2) && is_array($res2)) {
            return count($res2) + count($res1);
        }
        return count($res1);
    }


    /**
     * 获取有效用户的配置
     */
    public static function getValidConfig(int $hall_id)
    {
        $config_info = Setting::where('key', self::SYERTEM_CONFIG)->where('hall_id', $hall_id)->select("value")->first();
        if (empty($config_info)) {
            return ['effective_bet_amount' => 0, 'deposit_amount' => 0];
        }
        $config_info = $config_info->toArray();
        $config = $config_info['value'];
        return json_decode($config, true);
    }

    /**
     * 获取代理的下级会员
     * @param int $agentId
     * @return array
     */
    public static function getAgentMember(int $agent_id, int $hall_id, string $end_time): array
    {
        $members = User::where('agent_id', $agent_id)->where('hall_id', $hall_id)->where('created_at', '<', $end_time)->select('id')->get();
        if (empty($members)) {
            return [];
        }
        $members = json_decode(json_encode($members), true);
        $user_ids = array_column($members, "id");
        return $user_ids;
    }

    /**
     * 获取本期总输赢，视讯，电竞，体验，电子，棋牌，彩票，有效投注
     * @param $agent_id
     * @param $currend_period_info
     * @param int $hall_id
     * @return array
     */
    public static function getGameDate($agent_id, $currend_period_info, int $hall_id): array
    {
        $startTime = date("Y-m-d", strtotime($currend_period_info['start_time']));
        $endTime = date("Y-m-d", strtotime($currend_period_info['end_time']) + 1);
        $user_ids = self::getAgentMember($agent_id, $hall_id, date("Y-m-d H:i:s", strtotime($currend_period_info['end_time']) + 1));
        if (empty($user_ids)) {
            return ['bet_times' => 0, 'bet_amount_egame' => 0, 'bet_amount_live' => 0, 'bet_amount_sport' => 0, 'bet_amount_esport' => 0, 'bet_amount_caipiao' => 0, 'bet_amount_qipai' => 0,
                'validbet_egame' => 0, 'validbet_live' => 0, 'validbet_sport' => 0, 'validbet_esport' => 0, 'validbet_caipiao' => 0, 'validbet_qipai' => 0, 'prize_egame' => 0, 'prize_live' => 0,
                'prize_sport' => 0, 'prize_esport' => 0, 'prize_caipiao' => 0, 'prize_qipai' => 0, 'profit_egame' => 0, 'profit_live' => 0, 'profit_sport' => 0, 'profit_esport' => 0, 'profit_caipiao' => 0,
                'profit_qipai' => 0, 'bonus_amount_egame' => 0, 'bonus_amount_live' => 0, 'bonus_amount_sport' => 0, 'bonus_amount_esport' => 0, 'bonus_amount_caipiao' => 0, 'bonus_amount_qipai' => 0,
                'totalprofit' => 0, 'totalvalidbet' => 0
            ];
        }
        $ids = implode(",", $user_ids);
        $sql = "select sum(bet_times) bet_times, 
        SUM(IF(game_type = 1, bet_amount, 0)) bet_amount_egame,
        SUM(IF(game_type = 2, bet_amount, 0)) bet_amount_live,
        SUM(IF(game_type = 3, bet_amount, 0)) bet_amount_sport,
        SUM(IF(game_type = 4, bet_amount, 0)) bet_amount_esport,
        SUM(IF(game_type = 5, bet_amount, 0)) bet_amount_caipiao,
        SUM(IF(game_type = 6, bet_amount, 0)) bet_amount_qipai,
        SUM(IF(game_type = 1, validbet, 0)) validbet_egame,
        SUM(IF(game_type = 2, validbet, 0)) validbet_live,
        SUM(IF(game_type = 3, validbet, 0)) validbet_sport,
        SUM(IF(game_type = 4, validbet, 0)) validbet_esport,
        SUM(IF(game_type = 5, validbet, 0)) validbet_caipiao,
        SUM(IF(game_type = 6, validbet, 0)) validbet_qipai,
        SUM(IF(game_type = 1, prize, 0)) prize_egame,
        SUM(IF(game_type = 2, prize, 0)) prize_live,
        SUM(IF(game_type = 3, prize, 0)) prize_sport,
        SUM(IF(game_type = 4, prize, 0)) prize_esport,
        SUM(IF(game_type = 5, prize, 0)) prize_caipiao,
        SUM(IF(game_type = 6, prize, 0)) prize_qipai,
        SUM(IF(game_type = 1, profit, 0)) profit_egame,
        SUM(IF(game_type = 2, profit, 0)) profit_live,
        SUM(IF(game_type = 3, profit, 0)) profit_sport,
        SUM(IF(game_type = 4, profit, 0)) profit_esport,
        SUM(IF(game_type = 5, profit, 0)) profit_caipiao,
        SUM(IF(game_type = 6, profit, 0)) profit_qipai,
        SUM(IF(game_type = 1, bonus_amount, 0)) bonus_amount_egame,
        SUM(IF(game_type = 2, bonus_amount, 0)) bonus_amount_live,
        SUM(IF(game_type = 3, bonus_amount, 0)) bonus_amount_sport,
        SUM(IF(game_type = 4, bonus_amount, 0)) bonus_amount_esport,
        SUM(IF(game_type = 5, bonus_amount, 0)) bonus_amount_caipiao,
        SUM(IF(game_type = 6, bonus_amount, 0)) bonus_amount_qipai,
        sum(profit) totalprofit,sum(validbet) totalvalidbet
        from report_partner_game where hall_id={$hall_id} and date >='{$startTime}' and date <'{$endTime}' and user_id in ({$ids})
         
           ";
        $res = DB::select($sql);
        return json_decode(json_encode($res[0]), true);
    }



    /**
     * 获取线下入款+人工存提 +线下入款  相关的记录
     * @param int $agent_id
     * @param array $money_type
     * @param array $period_info
     * @param int $hall_id
     * @param int $type type:0 线下 1 线上
     * @param string $field amount 存入金额  coupon_amount 优惠金额
     * @return int
     */
    public static function getMoneyDepositLog(int $agent_id, array $money_type, array $period_info, int $hall_id, int $type = 0, string $field = 'amount', int $is_active = 0): int
    {
        $startTime = date("Y-m-d H:i:s", strtotime($period_info['start_time']));
        $endTime = date("Y-m-d H:i:s", strtotime($period_info['end_time']) + 1);
        $user_ids = self::getAgentMember($agent_id, $hall_id, date("Y-m-d H:i:s", strtotime($period_info['end_time']) + 1));
        if (empty($user_ids)) {
            return 0;
        }
        $query=MoneyDeposit::where("status",MoneyDepositEnum::STATUS_PAID)->where("hall_id",$hall_id)->where("recharge_time",">=",$startTime)
            ->where("recharge_time",'<',$endTime)->whereIn("user_id",$user_ids);
        if (!$is_active) {
            if (!$type && !empty($money_type)) {//线下逻辑
                $query->whereIn("offline_pay_type",$money_type);
            } else {
                $query->where("is_online",$type);
            }
        }
        if ($is_active && !empty($money_type)) {//统计优惠
            $query->where("active_id",'>',MoneyDepositEnum::STATUS_PENDING)->whereNotIn('offline_pay_type',$money_type);//此处还要排除手动存款的优惠避免重复计算
        }
        $result = $query->selectRaw("IFNULL(sum({$field}),0) money")->first();
        if (!empty($result)) {
            return (int)($result->money);
        }
        return 0;
    }


    /**
     * 获取优惠活动的金额
     * @param int $agent_id
     * @param array $period_info
     * @return int
     */
    public static function getActivityMoney(int $agent_id,array $period_info,int $hall_id,array $active_type):int
    {
        $startTime = date("Y-m-d H:i:s", strtotime($period_info['start_time']));
        $endTime = date("Y-m-d H:i:s", strtotime($period_info['end_time']) + 1);
        $user_ids = self::getAgentMember($agent_id, $hall_id, date("Y-m-d H:i:s", strtotime($period_info['end_time']) + 1));
        if (empty($user_ids)) {
            return 0;
        }
        $result = ActiveRecord::where("status",MoneyDepositEnum::STATUS_PAID)->where("hall_id",$hall_id)
             ->where("created_at",">=",$startTime)->where("updated_at",'<',$endTime)
            ->selectRaw("IFNULL(sum(amount),0) money")->whereIn('template_id',$active_type)->whereIn('user_id',$user_ids)
            ->first();
        if (!empty($result)) {
            return (int)($result->money);
        }
        return 0;
    }





    /**
     * 获取出款相关的记录
     * @param int $agent_id
     * @param array $type
     * @param array $period_info
     * @param int $hall_id
     * @return int
     */
    public static function getMoneyWithdrawLog(int $agent_id, array $type, array $period_info, int $hall_id): int
    {
        $startTime = date("Y-m-d H:i:s", strtotime($period_info['start_time']));
        $endTime = date("Y-m-d H:i:s", strtotime($period_info['end_time']) + 1);
        $user_ids = self::getAgentMember($agent_id, $hall_id, date("Y-m-d H:i:s", strtotime($period_info['end_time']) + 1));
        if (empty($user_ids)) {
            return 0;
        }
        $result = MoneyWithdraw::where("status",MoneyWithdrawEnum::WITHDRAW_STATUS_PAID)->where("hall_id",$hall_id)->where("confirm_time",">=",$startTime)
            ->where("confirm_time",'<',$endTime)->whereIn("user_id",$user_ids)->whereIn("type",$type)->selectRaw("IFNULL(sum(amount),0) money")->first();
        if (!empty($result)) {
            return (int)($result->money);
        }
        return 0;
    }


    /**
     * 获取手续费设置
     * @return array
     */
    public static function getFeeConfig(int $hall_id): array
    {
        $result = AgentBkgeFeeSetting::where('hall_id', $hall_id)->where("status", 1)->selectRaw("deposit_fee_per,deposit_max_limit,withdraw_fee_per,withdraw_max_limit")->first();
        if (empty($result)) {
            return ['deposit_fee_per' => 0, 'deposit_max_limit' => 0, 'withdraw_fee_per' => 0, 'withdraw_max_limit' => 0];
        }
        return $result->toArray();
    }


    /**
     * 获取出入款手续费
     * @param $deposit_money
     * @param $withdraw_money
     * @param $fee_config
     * @return int
     */
    public static function getOrgFee($deposit_money, $withdraw_money, $fee_config): int
    {
        $depositFee = $deposit_money * $fee_config['deposit_fee_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES;
        $withdrawFee = $withdraw_money * $fee_config['withdraw_fee_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES;
        $depositFee = $depositFee <= $fee_config['deposit_max_limit'] ? $depositFee : $fee_config['deposit_max_limit'];
        $withdrawFee = $withdrawFee <= $fee_config['withdraw_max_limit'] ? $withdrawFee : $fee_config['withdraw_max_limit'];
        return (int)($depositFee + $withdrawFee);
    }


    /**
     * 判断是否存在还有上期转下期的数据
     * @param int $agent_id
     * @return array
     */
    public static function LastPeriodData(int $agent_id, int $hall_id): array
    {
        $data = AgentBkgeRecord::where("hall_id", $hall_id)->where("agent_id", $agent_id)->orderBy("id", "desc")->first();
        if (empty($data)) {
            return [];
        }
        $data = $data->toArray();
        if ($data['status'] != 3) {//3为上期转下期
            return [];
        }
        return $data;
    }


    /**
     * 获取本期退水比例
     * @param array $agent_info
     * @return array
     */
    public static function getCurrentRebetRate(array $agent_info, int $validbet_min, int $hall_id): array
    {
        $setting = ['sport_per' => 0, 'egame_per' => 0, 'lottery_per' => 0, 'video_per' => 0, 'esport_per' => 0, 'card_per' => 0];
        $templateId = (int)$agent_info['rebet_template_id'];
         if(!$templateId){
             return $setting;
         }
        $where = [['hall_id', '=', $hall_id], ['template_id', '=', $templateId]];
        $bage_setting = AgentRebetSetting::where($where)->selectRaw("sport_per,egame_per,lottery_per,video_per,esport_per,card_per,validbet_min,id")->get();
        if (empty($bage_setting)) {
            return $setting;
        }
        $result = [];//接收其满足的范围
        $set = [];
        $bage_setting = json_decode(json_encode($bage_setting), true);
        foreach ($bage_setting as $value) {
            $set[$value['id']] = $value;
            if ($validbet_min >= $value['validbet_min']) {
                $result[$value['id']] = $value['validbet_min'];
            }
        }
        if (empty($result)) {
            return $setting;
        }
        //多个档次已公司输赢最高为准
        arsort($result);
        foreach ($result as $key => $values) {
            $setting = $set[$key];
            break;
        }
        return $setting;

    }


    /**
     * 计算本期退水金额
     * @param array $config
     * @param int $valid
     * @return int
     */
    public static function getCurrentRebetMoney(array $config, int $current_validbet_egame, int $current_validbet_live, int $current_validbet_sport, int $current_validbet_esport, int $current_validbet_caipiao, int $current_validbet_qipai): int
    {

        $money = $current_validbet_egame * $config['egame_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES + $current_validbet_live * $config['video_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES + $current_validbet_sport * $config['sport_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES + $current_validbet_esport * $config['esport_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES + $current_validbet_caipiao * $config['lottery_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES + $current_validbet_qipai * $config['card_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES;
        return (int)$money;
    }


    /**
     * 获取本期退佣比例
     * @param array $agent_info
     * @param $profit_min 公司盈利金额最小值 单位厘
     * @param $valid_user_min 有效会员数最小值
     * @param $validbet_min 总有效投注最小值
     * @param $hall_id
     * @return array
     */
    public static function getCurrentBkgeRate(array $agent_info, int $profit_min, int $valid_user_min, int $validbet_min, int $hall_id): array
    {
        $setting = ['sport_per' => 0, 'egame_per' => 0, 'lottery_per' => 0, 'video_per' => 0, 'esport_per' => 0, 'card_per' => 0];
        $templateId = (int)$agent_info['bkge_template_id'];
        if(!$templateId){
            return $setting;
        }
        $where = [['hall_id', '=', $hall_id], ['template_id', '=', $templateId]];
        $bage_setting = AgentBkgeSetting::where($where)->selectRaw("id,sport_per,egame_per,lottery_per,video_per,esport_per,card_per,profit_min,valid_user_min,validbet_min")->get();
        if (empty($bage_setting)) {
            return $setting;
        }
        $result = [];//接收其满足的范围
        $set = [];
        $bage_setting = json_decode(json_encode($bage_setting), true);
        foreach ($bage_setting as $value) {
            $set[$value['id']] = $value;
            if ($profit_min >= $value['profit_min'] && $valid_user_min >= $value['valid_user_min'] && $validbet_min >= $value['validbet_min']) {
                $result[$value['id']] = $value['profit_min'];
            }
        }
        if (empty($result)) {
            return $setting;
        }
        //多个档次已公司输赢最高为准
        arsort($result);
        foreach ($result as $key => $values) {
            $setting = $set[$key];
            break;
        }
        return $setting;
    }

    /**
     * 计算本期退佣金额
     * @param array $config
     * @param int $fee
     * @param int $total_profit_egame
     * @param int $total_profit_live
     * @param int $total_profit_sport
     * @param int $total_profit_esport
     * @param int $total_profit_caipiao
     * @param int $total_profit_qipai
     * @return int
     */
    public static function currentBkgeMoney(array $config, int $fee, int $total_profit_egame, int $total_profit_live, int $total_profit_sport, int $total_profit_esport, int $total_profit_caipiao, int $total_profit_qipai): int
    {
        $real_profit_live = $total_profit_live;
        $real_profit_esport = $total_profit_esport;
        $real_profit_sport = $total_profit_sport;
        $real_profit_egame = $total_profit_egame;
        $real_profit_card = $total_profit_qipai;
        $real_profit_lottery = $total_profit_caipiao;

        if ($total_profit_live > 0 && $fee > 0) {
            $real_profit_live = $total_profit_live - $fee > 0 ? $total_profit_live - $fee : 0;
            $fee = $total_profit_live - $fee > 0 ? 0 : $fee - $total_profit_live;
        }
        if ($total_profit_esport > 0 && $fee > 0) {
            $real_profit_esport = $total_profit_esport - $fee > 0 ? $total_profit_esport - $fee : 0;
            $fee = $total_profit_esport - $fee > 0 ? 0 : $fee - $total_profit_esport;
        }
        if ($total_profit_sport > 0 && $fee > 0) {
            $real_profit_sport = $total_profit_sport - $fee > 0 ? $total_profit_sport - $fee : 0;
            $fee = $total_profit_sport - $fee > 0 ? 0 : $fee - $total_profit_sport;
        }
        if ($total_profit_egame > 0 && $fee > 0) {
            $real_profit_egame = $total_profit_egame - $fee > 0 ? $total_profit_egame - $fee : 0;
            $fee = $total_profit_egame - $fee > 0 ? 0 : $fee - $total_profit_egame;
        }
        if ($total_profit_qipai > 0 && $fee > 0) {
            $real_profit_card = $total_profit_qipai - $fee > 0 ? $total_profit_qipai - $fee : 0;
            $fee = $total_profit_qipai - $fee > 0 ? 0 : $fee - $total_profit_qipai;
        }
        if ($total_profit_caipiao > 0 && $fee > 0) {
            $real_profit_lottery = $total_profit_caipiao - $fee > 0 ? $total_profit_caipiao - $fee : 0;
            $fee = $total_profit_caipiao - $fee > 0 ? 0 : $fee - $total_profit_caipiao;
        }

        $money = ($real_profit_live) * $config['video_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES + ($real_profit_esport) * $config['esport_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES + ($real_profit_sport) * $config['sport_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES + ($real_profit_egame) * $config['egame_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES + ($real_profit_card) * $config['card_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES + ($real_profit_lottery) * $config['lottery_per'] / CommonEnum::PERCENT_TIMES / CommonEnum::PERCENT_TIMES;
        return (int)$money;
    }


    /**
     * 自动发放退佣佣金
     * @param int $id
     */
    public static function autoSendBage(array $params, int $bkge_money)
    {
        return DB::update("update agent_money set balance_before=`balance`,balance=`balance`+{$bkge_money}  where agent_id=" . $params['id'] . '  and hall_id=' . $params['hall_id']);
    }


    /**
     * 发送佣金
     * 添加资金流水记录
     * @param $db
     * @param array $params
     *
     */
    public static function addBkgeMoneyLog(array $params)
    {
        //添加流水记录
        $result = DB::table("agent_money_log")->insertGetId($params);
        return $result;
    }

    /**
     * 新增统计记录
     * @param array $data
     */
    public static function addBkgeLog(array $data)
    {
        //添加流水记录
        $result = [];
        $insertFilter1 = ['hall_id', 'period_id', 'agent_id', 'agent_name', 'total_valid_user', 'total_bet_times', 'total_bet_amount', 'total_validbet_amount', 'total_profit_amount', 'total_bkge_amount', 'lottery_bkge_per', 'egame_bkge_per', 'sport_bkge_per', 'video_bkge_per', 'esport_bkge_per', 'card_bkge_per', 'lottery_rebet_per', 'egame_rebet_per', 'sport_rebet_per', 'video_rebet_per', 'esport_rebet_per', 'card_rebet_per'];
        $insertFilter2 = ['deposit_fee_per', 'withdraw_fee_per', 'current_validbet_lottery', 'current_validbet_egame', 'current_validbet_sport', 'current_validbet_video', 'current_validbet_esport', 'current_validbet_card', 'current_validbet_amount', 'current_profit_lottery', 'current_profit_egame', 'current_profit_sport', 'current_profit_video', 'current_profit_esport', 'current_profit_card', 'current_prifit_amount', 'current_fee_amount', 'current_deposit_amount', 'current_withdraw_amount', 'current_coupon_amount', 'current_rebet_amount', 'current_reverse_amount', 'previous_validbet_lottery'];
        $insertFilter3 = ['previous_validbet_egame', 'previous_validbet_sport', 'previous_validbet_video', 'previous_validbet_esport', 'previous_validbet_card', 'previous_validbet_amount', 'previous_profit_lottery', 'previous_profit_egame', 'previous_profit_sport', 'previous_profit_video', 'previous_profit_esport', 'previous_profit_card', 'previous_prifit_amount', 'previous_fee_amount', 'previous_deposit_amount', 'previous_withdraw_amount', 'previous_coupon_amount', 'previous_rebet_amount', 'previous_reverse_amount', 'status', 'setting'];
        $insertFilter1 = array_merge($insertFilter1, $insertFilter2, $insertFilter3);

        foreach ($data as $value) {
            $result[] = array_combine($insertFilter1, $value);
        }
        $result = DB::table('agent_bkge_record')->insert($result);
        return $result;
    }


    /**
     * 修改本期的状态
     * @param int $period
     * @return bool
     */
    public static function updatePerionStatus(int $period, int $hall_id): bool
    {
        return DB::table('agent_bkge_period')->whereRaw("status=0  and id ={$period} and hall_id={$hall_id} ")->update(['status' => 1]);
    }

    /**
     * 将本期的费率计算统计到表中
     * @param int $period_id
     * @param array $param
     */
    public static function addSettingLog(int $period_id, array $param, int $hall_id)
    {
        $data = AgentBkgeFeeSettingLog::where("hall_id", $hall_id)->where('period_id', $period_id)->first();
        if (empty($data)) {
            $param['hall_id'] = $hall_id;
            $param['period_id'] = $period_id;
            $param['admin_user_id'] = 1;
            $param['admin_username'] = "管理员";
            return DB::table('agent_bkge_fee_setting_log')->insert($param);
        }
        return AgentBkgeFeeSettingLog::where("hall_id", $hall_id)->where('period_id', $period_id)->update($param);
    }

    /**
     * 获取往期待统计的数据
     * 只统计那些状态未统计的统计时间小于当前时间的
     * @param int $hall_id
     * @return array
     */
    public static function getPreNotHandlePeriod(int $hall_id): array
    {
        $time = time();
        $data = AgentBkgePeriod::where('hall_id', $hall_id)->where("status", 0)->whereRaw("unix_timestamp(handle_time) <{$time}")->orderBy("id", "asc")->get();
        if (!empty($data)) {
            return $data->toArray();
        }
        return [];
    }


}